package com.lichuan.utils;

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ConnectException;
import java.util.Date;

public class OpenOfficeToPDF {
    public static void docToPdf(File inputFile, File outputFile) {

        OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
        System.out.println(connection.isConnected());
        try {
            connection.connect();
            DocumentConverter converter = new OpenOfficeDocumentConverter(
                    connection);
            converter.convert(inputFile, outputFile);
        } catch (ConnectException cex) {
            cex.printStackTrace();
        } finally {
            // close the connection
            if (connection != null) {
                connection.disconnect();
                connection = null;
            }
        }
    }

    /*转PDF格式值*/
    private static final int wdFormatPDF = 17;
    private static final int xlFormatPDF = 0;
    private static final int ppFormatPDF = 32;
    private static final int msoTrue = -1;
    private static final int msofalse = 0;

    /*转HTML格式值*/
    private static final int wdFormatHTML = 8;
    private static final int ppFormatHTML = 12;
    private static final int xlFormatHTML = 44;

    /*转TXT格式值*/
    private static final int wdFormatTXT = 2;

    public boolean convert2PDF(String inputFile, String pdfFile) {
        String suffix = getFileSufix(inputFile);
        File file = new File(inputFile);
        if (!file.exists()) {
            // System.out.println("文件不存在！");
            return false;
        }
        if (suffix.equals("pdf")) {
            //System.out.println("PDF not need to convert!");  
            return false;
        }
        if (suffix.equals("doc") || suffix.equals("docx") || suffix.equals("txt")) {
            return word2PDF(inputFile, pdfFile);
        } else if (suffix.equals("ppt") || suffix.equals("pptx")) {
            return ppt2PDF(inputFile, pdfFile);
        } else if (suffix.equals("xls") || suffix.equals("xlsx")) {
            return excel2PDF(inputFile, pdfFile) != -1;

        } else if (suffix.equals("jpg") || suffix.equals("png")) {
            return image2PDF(inputFile, pdfFile);
        } else {
            // System.out.println("文件格式不支持转换!");
            return false;
        }
    }

    /**
     * 获取文件后缀
     *
     * @param fileName
     * @return
     * @author SHANHY
     */
    private String getFileSufix(String fileName) {
        int splitIndex = fileName.lastIndexOf(".");
        return fileName.substring(splitIndex + 1);
    }

    /**
     * Word文档转换
     *
     * @param inputFile
     * @param pdfFile
     * @author SHANHY
     */
    public static boolean word2PDF(String inputFile, String pdfFile) {
        ComThread.InitSTA(false);

        long start = System.currentTimeMillis();
        ActiveXComponent app = null;
        Dispatch doc = null;
        try {
            app = new ActiveXComponent("Word.Application");// 创建一个word对象  
            app.setProperty("Visible", new Variant(false)); // 不可见打开word  
            app.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏  
            Dispatch docs = app.getProperty("Documents").toDispatch();// 获取文挡属性  

            //System.out.println("打开文档 >>> " + inputFile);  
            // Object[]第三个参数是表示“是否只读方式打开”  
            // 调用Documents对象中Open方法打开文档，并返回打开的文档对象Document  
            doc = Dispatch.call(docs, "Open", inputFile, false, true).toDispatch();
            // 调用Document对象的SaveAs方法，将文档保存为pdf格式  
            //System.out.println("转换文档 [" + inputFile + "] >>> [" + pdfFile + "]");  
            Dispatch.call(doc, "SaveAs", pdfFile, wdFormatPDF);//word保存为pdf格式宏，值为17  
//            Dispatch.call(doc, "ExportAsFixedFormat", pdfFile, wdFormatPDF); // word保存为pdf格式宏，值为17  

            long end = System.currentTimeMillis();

            //System.out.println("用时：" + (end - start) + "ms.");  
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            //  System.out.println("========Error:文档转换失败：" + e.getMessage());
        } finally {
            Dispatch.call(doc, "Close", false);
            //System.out.println("关闭文档");  
            if (app != null)
                app.invoke("Quit", new Variant[]{});
        }
        // 如果没有这句话,winword.exe进程将不会关闭  
        ComThread.Release();
        ComThread.quitMainSTA();
        return false;
    }

    /**
     * PPT文档转换
     *
     * @param inputFile
     * @param pdfFile
     * @author SHANHY
     */
    public static boolean ppt2PDF(String inputFile, String pdfFile) {
        ComThread.InitSTA();

        long start = System.currentTimeMillis();
        ActiveXComponent app = null;
        Dispatch ppt = null;
        try {
            app = new ActiveXComponent("PowerPoint.Application");// 创建一个PPT对象  
            // app.setProperty("Visible", new Variant(false)); // 不可见打开（PPT转换不运行隐藏，所以这里要注释掉）  
            // app.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏  
            Dispatch ppts = app.getProperty("Presentations").toDispatch();// 获取文挡属性  

            //System.out.println("打开文档 >>> " + inputFile);  
            // 调用Documents对象中Open方法打开文档，并返回打开的文档对象Document  
            ppt = Dispatch.call(ppts, "Open", inputFile,
                    true,// ReadOnly  
                    true,// Untitled指定文件是否有标题  
                    false// WithWindow指定文件是否可见  
            ).toDispatch();

            // System.out.println("转换文档 [" + inputFile + "] >>> [" + pdfFile + "]");
            Dispatch.call(ppt, "SaveAs", pdfFile, ppFormatPDF);

            long end = System.currentTimeMillis();

            // System.out.println("用时：" + (end - start) + "ms.");

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            // System.out.println("========Error:文档转换失败：" + e.getMessage());
        } finally {
            Dispatch.call(ppt, "Close");
            //System.out.println("关闭文档");  
            if (app != null)
                app.invoke("Quit", new Variant[]{});
        }
        ComThread.Release();
        ComThread.quitMainSTA();
        return false;
    }

    /**
     * Excel文档转换
     *
     * @param inputFile
     * @param pdfFile
     * @author SHANHY
     */
    public static Integer excel2PDF(String inputFile, String pdfFile) {
        try {

            //ComThread.InitSTA(true);
            ActiveXComponent ax = new ActiveXComponent("Excel.Application");
            //  System.out.println("开始转化Excel为PDF...");
            long date = new Date().getTime();
            ax.setProperty("Visible", false);
            ax.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏
            Dispatch excels = ax.getProperty("Workbooks").toDispatch();

            Dispatch excel = Dispatch
                    .invoke(excels, "Open", Dispatch.Method,
                            new Object[]{inputFile, new Variant(false), new Variant(false)}, new int[9])
                    .toDispatch();
            // 转换格式
            Dispatch.invoke(excel, "ExportAsFixedFormat", Dispatch.Method, new Object[]{new Variant(0), // PDF格式=0
                    pdfFile, new Variant(0) // 0=标准 (生成的PDF图片不会变模糊) 1=最小文件
                    // (生成的PDF图片糊的一塌糊涂)

            }, new int[1]);
            // System.out.println("Excel为PDF完成...");
            // 这里放弃使用SaveAs
            /*
             */
            long date2 = new Date().getTime();
            int time = (int) ((date2 - date) / 1000);
            Dispatch.call(excel, "Close", new Variant(false));

            if (ax != null) {
                ax.invoke("Quit", new Variant[]{});
                ax = null;
            }
            ComThread.Release();
            return time;
        } catch (Exception e) {
            // TODO: handle exception
            return -1;
        }
    }


    public static  boolean image2PDF(String source, String target) {
        try {
            Image image = Image.getInstance(source);
            //获取图片尺寸
            float img_width = image.getWidth();
            float img_height = image.getHeight();
            float percent = PageSize.A4.getWidth()/img_width;
            Document imgToPdfDoc = new Document(new Rectangle(PageSize.A4.getWidth()+20, img_height * percent+20), 10, 10, 10, 10);
            imgToPdfDoc.newPage();
            PdfWriter.getInstance(imgToPdfDoc, new FileOutputStream(target));
            imgToPdfDoc.open();
            image.setAlignment(Image.MIDDLE);
            image.scalePercent(PageSize.A4.getWidth()/img_width*100);
            imgToPdfDoc.add(image);
            imgToPdfDoc.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } catch (DocumentException e) {
            e.printStackTrace();
            return false;
        }
    }

    public static void main(String[] args) {
        String src = "D:\\testPath\\te\\55.jpg";
        String dest = "D:\\testPath\\te\\55.pdf";
        String src1 = "D:\\testPath\\te\\1.png";
        String dest1 = "D:\\testPath\\te\\1.pdf";
        image2PDF(src, dest);
        image2PDF(src1, dest1);


    }


}
